package com.zhisolution.zhicms.freemarker;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.zhisolution.zhicms.ZhiCmsInterceptor;
import com.zhisolution.zhicms.util.StringUtil;

import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 根据表名查询List
 * 
 * @author hym
 * <@table_list table='sys_column' rows='10' asc='id'>
    	<#list table_list as list>
    		${list.name}
    	</#list>
    </@table_list>
 */
@SuppressWarnings("rawtypes")
public class Table_List implements TemplateDirectiveModel {

	public void execute(freemarker.core.Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String table = params.get("table") != null ? params.get("table").toString() : null;
		String offset = params.get("offset") != null ? params.get("offset").toString() : null;
		String rows = params.get("rows") != null ? params.get("rows").toString() : null;
		String asc = params.get("asc") != null ? params.get("asc").toString() : null;
		String desc = params.get("desc") != null ? params.get("desc").toString() : null;

		if (StringUtil.isNotBlank(table)) {
			StringBuffer sql = new StringBuffer();
			sql.append("select * from ");
			sql.append(table);
			if (StringUtil.isNotBlank(asc)) {
				sql.append(" ORDER BY ");
				sql.append(asc);
				sql.append(" ASC ");
			} else if (StringUtil.isNotBlank(desc)) {
				sql.append(" ORDER BY ");
				sql.append(desc);
				sql.append(" DESC ");
			}
			if (StringUtil.isNotBlank(rows)) {
				sql.append(" LIMIT ");
				if (StringUtil.isNotBlank(offset)) {
					sql.append(offset + ",");
				}
				sql.append(rows);
			}
			List list = Db.find(sql.toString());
			env.setVariable(ZhiCmsInterceptor.TABLE_LIST, ObjectWrapper.DEFAULT_WRAPPER.wrap(list));
			body.render(env.getOut());
		}

	}
}